package com.yz365.demo;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.util.Base64;
import android.util.Log;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yz365.demo.databinding.ActivityMainBinding;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "MainActivity";
    private ActivityMainBinding binding;
    private ExecutorService executorService = Executors.newFixedThreadPool(1);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_main);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
        this.handleBtn();
    }


    @Override
    public void onClick(View view) {
        // 未安装 云诊365，去浏览器下载
        if (view.getId() == R.id.btn_download_yz365) {
            openInBrowser(Yz365Constant.APP_DOWNLOAD_URL);
        }
        // 已安装 云诊365，使用schemes拉起
        else if (view.getId() == R.id.btn_open_yz365) {
            this.openYz365();
        }
    }

    private void handleBtn() {
        if (this.yz365Installed()) {
            binding.btnDownloadYz365.setVisibility(View.GONE);
            binding.btnOpenYz365.setVisibility(View.VISIBLE);

            binding.btnDownloadYz365.setOnClickListener(null);
            binding.btnOpenYz365.setOnClickListener(this);
        } else {
            binding.btnDownloadYz365.setVisibility(View.VISIBLE);
            binding.btnOpenYz365.setVisibility(View.GONE);

            binding.btnDownloadYz365.setOnClickListener(this);
            binding.btnOpenYz365.setOnClickListener(null);
        }
    }

    /**
     * 打开云诊365
     */
    private void openYz365() {
        executorService.execute(() -> {
            String appToken = this.getAppToken();
            String userTicket = this.getUserTicket(appToken);
            //
            String uriStr = String.format("%s://%s/partner/userLogin?ticket=%s",
                    Yz365Constant.APP_SCHEME,
                    "com.tongueai.yz365",
                    userTicket);
            Intent intent = new Intent();
            intent.setData(Uri.parse(uriStr));
            startActivity(intent);
        });
    }

    /**
     * 判断手机上是否已安装 云诊365
     *
     * @return
     */
    private boolean yz365Installed() {
        try {
            this.getPackageManager().getPackageInfo(Yz365Constant.APP_ID, 0);
        } catch (PackageManager.NameNotFoundException e) {
            Log.e(TAG, "yz365Installed: getPackageInfo error", e);
            return false;
        }
        return true;
    }

    private void openInBrowser(String uriString) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(uriString));
        startActivity(intent);
    }

    private String getAppToken() {
        try {
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json");
            //
            Map<String, String> enc = new HashMap<>();
            enc.put("timestamp", System.currentTimeMillis() + "");
            enc.put("appSecret", Yz365Constant.DEV_SECRET);
            String encStr = AesSimpleUtil.encrypt(new Gson().toJson(enc), Yz365Constant.AESKEY);
            //
            Map<String, String> body = new HashMap<>();
            body.put("appType", "PARTNER");
            body.put("appId", Yz365Constant.DEV_ID);
            body.put("encryptData", Base64.encodeToString(encStr.getBytes(StandardCharsets.UTF_8), Base64.NO_WRAP));
            //
            RequestBody requestBody = RequestBody.create(mediaType, new Gson().toJson(body));
            Request request = new Request.Builder()
                    .url(Yz365Constant.BASE_PATH + "outApp/token/login")
                    .post(requestBody)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("tenant-id", "10000")
                    .build();
            Response response = client.newCall(request).execute();
            String res = response.body().string();
            Log.i(TAG, "getAppToken: " + res);
            JsonObject jsonObject = JsonParser.parseString(res).getAsJsonObject();
            return jsonObject.get("data").getAsString();
        } catch (Exception e) {
            Log.e(TAG, "getAppToken: error", e);
            return null;
        }
    }

    private String getUserTicket(String appToken) {
        try {
            OkHttpClient client = new OkHttpClient();
            MediaType mediaType = MediaType.parse("application/json");
            Editable text = binding.editTextPhone.getText();

            //
            Map<String, String> enc = new HashMap<>();
            enc.put("mobile", text.toString());
            String encStr = AesSimpleUtil.encrypt(new Gson().toJson(enc), Yz365Constant.AESKEY);
            //
            Map<String, String> body = new HashMap<>();
            body.put("encryptData", encStr);
            //
            RequestBody requestBody = RequestBody.create(mediaType, new Gson().toJson(body));
            Request request = new Request.Builder()
                    .url(Yz365Constant.BASE_PATH + "outApp/partner/user/ticket")
                    .post(requestBody)
                    .addHeader("Content-Type", "application/json")
                    .addHeader("tenant-id", "10000")
                    .addHeader("yz365-token", appToken)
                    .build();
            Response response = client.newCall(request).execute();
            String res = response.body().string();
            Log.i(TAG, "getUserTicket: " + res);
            JsonObject jsonObject = JsonParser.parseString(res).getAsJsonObject();
            return jsonObject.get("result").getAsString();
        } catch (Exception e) {
            Log.e(TAG, "getUserTicket: error", e);
            return null;
        }
    }
}